<?php

    ##################################################
    #
    # Copyright (c) 2004-2006 OIC Group, Inc.
    # Written and Designed by Adam Kessler
    #
    # This file is part of Exponent
    #
    # Exponent is free software; you can redistribute
    # it and/or modify it under the terms of the GNU
    # General Public License as published by the Free
    # Software Foundation; either version 2 of the
    # License, or (at your option) any later version.
    #
    # GPL: http://www.gnu.org/licenses/gpl.txt
    #
    ##################################################
    /**
    * Aug 30, 2012 - trungdt - Comment some un-used functions
    */
    
    function redirect_to(array $parms=array()) {
        if (count($parms) == 0) return false;
        global $router;
        header("Location: " . $router->makeLink($parms));
        exit();
    }	

    function flash($name="", $msg) {
        if ($name == "") return false;
        $flash = exponent_sessions_get('flash');
        $flash[$name] = $msg;
        exponent_sessions_set('flash', $flash);
    }

    function flushFlash() {
        exponent_sessions_set('flash', array());
    }

    function show_msg_queue() {
        $queues = exponent_sessions_get('flash');
        if (!empty($queues)) {
            $template = new template('common','_msg_queue');
            $template->assign('queues', exponent_sessions_get('flash'));
            $html = $template->render();
        } else {
            $html = '';
        }
        flushFlash();
        return $html;
    }

    function get_template_for_action($controller, $action) {
        $loc->mod = $controller;
        $loc->src = '';
        $loc->int = '';

        if (file_exists(BASE.'views/'.$controller.'/'.$action.'.tpl')) {
            return new template($controller, $action, $loc, false, 'controllers');
        } elseif (file_exists(BASE.'views/scaffold/'.$action.'.tpl')) {
            return new template('scaffold', $action, $loc, false, 'controllers');
        } else {
            return new template('scaffold', 'blank', $loc, false, 'controllers');
        }

    }

    function makeLocation($mod=null,$src=null,$int=null) {
        $loc = null;
        $loc->mod = ($mod ? $mod : "");
        $loc->src = ($src ? $src : "");
        $loc->int = ($int ? $int : "");
        return $loc;
    }

    function object2Array($object=null) {
        $ret_array = array();
        if(empty($object)) return $ret_array;

        foreach($object as $key=>$value) {
            $ret_array[$key] = $value;
        }

        return $ret_array;
    }

    // Sept 14, 2010: immanuel192 update this line, support automatic text to vietnamese translate - begin
    /**
    * This function remove all Vietnamese text mark
    * Will be removed
    *   - Vietnamese text mark
    *   - Space
    *   - Marks: ? < > : ; " ' [ ] { } ~ ! @ # $ % ^ & * ( ) ` , . \ /
    * 
    * @param string $source
    * @param int $to_lower =1: change result to lower case
    */
    function _to_vietnamese_with_nomark($source, $to_lower=0)
    {
        /*
        Change log
        June 8: use iconv instead of replace

        // Vietnamese text mark remove 
        $aRemove=array("/(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)/"=>'a',
        "/(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)/"=>'e',
        "/(ì|í|ị|ỉ|ĩ)/"=>'i',
        "/(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)/"=>'o',
        "/(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)/"=>'u',
        "/(ỳ|ý|ỵ|ỷ|ỹ)/"=>'y',
        "/(đ)/"=>'d',
        "/(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)/"=>'A',
        "/(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)/"=>'E',
        "/(Ì|Í|Ị|Ỉ|Ĩ)/"=>'I',
        "/(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)/"=>'O',
        "/(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)/"=>'U',
        "/(Ỳ|Ý|Ỵ|Ỷ|Ỹ)/"=>'Y',
        "/(Đ)/"=> 'D',
        "/( )/"=>"-");
        // space and some other marks remove
        foreach ($aRemove as $marks=>$v)
        {
        $source = preg_replace("{$marks}i",$v,$source);
        }
        */

        $source = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $source);

        // 2010/10/12 - immanuel192 - add remove / because of confict with SEF_URL - begin
        $source=str_replace("/","_",$source);
        $source=str_replace(",","_",$source);
        $source=str_replace(".","_",$source);
        $source=str_replace("'","_",$source);
        $source=str_replace('"',"_",$source);
        $source=str_replace('?',"_",$source);
        $source=str_replace('+',"_",$source);
        $source=str_replace('>',"_",$source);
        $source=str_replace('<',"_",$source);
        $source=str_replace('/',"_",$source);
        $source=str_replace('\\',"_",$source);
        $source=str_replace('[',"_",$source);
        $source=str_replace(']',"_",$source);
        $source=str_replace('{',"_",$source);
        $source=str_replace('}',"_",$source);
        $source=str_replace('~',"_",$source);
        $source=str_replace('@',"_",$source);
        $source=str_replace('%',"_",$source);
        $source=str_replace('^',"_",$source);
        $source=str_replace('&',"_",$source);
        $source=str_replace('$',"_",$source);
        $source=str_replace('|',"_",$source);
        $source=str_replace('(',"_",$source);
        $source=str_replace(')',"_",$source);
        $source=str_replace(' ',"-",$source);
        // 2010/10/12 - immanuel192 - add remove / because of confict with SEF_URL - end
        if ($to_lower != 0)
            $source=strtolower($source);
        return $source;
    }

    // Feb 11, 2011 - trungdt - add function remove html in safe way, because sometime, PHP confict with UTF-8
    /**
    * ABSoft: Remove all un-safe HTML chars
    * 
    */
    function _ab_safe_html_string($string){
        $temp=str_replace('"',"&quot;",$string);
        $temp=str_replace("'","&#39;",$temp);
        return $temp;
    }

    define("AB_THEME_ACTION_CACHE","_AB_THEME_ACTION_CACHE");
    define("AB_THEME_ACTION_DES_CACHE","_AB_THEME_ACTION_DES_CACHE");
    define("AB_THEME_ACTION_TITLE_CACHE","_AB_THEME_ACTION_CACHE_TITLE");
    define("AB_THEME_META_OG_TITLE_CACHE","_AB_THEME_META_OG_TITLE_CACHE");
    define("AB_THEME_META_OG_CONTENT_CACHE","_AB_THEME_META_OG_CONTENT_CACHE");
    define("AB_THEME_META_OG_IMAGE","_AB_THEME_META_OG_IMAGE");

    function _ab_theme_action_push_content()
    {
        $temp=ob_get_clean();
        exponent_sessions_set("_AB_THEME_ACTION_CACHE",$temp);
    }

    /**
    * This function set the OG Meta Content for facebook share
    * @author trungdt
    * @since June 21, 2011
    * 
    * @param $type =0: Content; =1: Title ; =2: Image
    */
    function _ab_theme_og_meta_set($value, $type = 0){
        $value=trim(strip_tags($value));
        if ($type == 0)
            exponent_sessions_set(AB_THEME_META_OG_CONTENT_CACHE,$value);
        else 
            if ($type ==1)
                exponent_sessions_set(AB_THEME_META_OG_TITLE_CACHE,$value);
            else if ($type == 2)
                    exponent_sessions_set(AB_THEME_META_OG_IMAGE,$value);
    }
    function _ab_theme_og_meta_get($type = 0)
    {
        $temp="";
        if ($type == 0)
            $temp=exponent_sessions_get(AB_THEME_META_OG_CONTENT_CACHE);
        else if ($type ==1)
                $temp=exponent_sessions_get(AB_THEME_META_OG_TITLE_CACHE);
            else if ($type ==2)
                {
                    $temp=exponent_sessions_get(AB_THEME_META_OG_IMAGE);
                    // incase that this url is not wellform, insert BASE_URL
                    if (($temp !=null) && (strpos($temp, "http:")===false))
                    {
                        $temp=BASE_URL."/".$temp;
                    }
            }

            if ($temp == null)
            $temp="";
        return $temp;
    }
    /**
    * 
    * @param mixed $title Your title 
    * @param mixed $page Your current page
    * 
    * Change logs
    * June 21, 2011 - trungdt - Add page into title, for difference page title
    * @param int $type = 1: title; =0 description
    */
    function _ab_theme_action_register_title($title, $page = 1, $type = 1){
        if ($type == 1)
        {
            if ($page > 1)
            {
                $title .=" - Trang {$page} ";
            }
            $title .=" - ".SITE_TITLE;
            exponent_sessions_set(AB_THEME_ACTION_TITLE_CACHE,$title);
            // June 21, 2011 - trungdt - Set meta OG title cache automatically
            exponent_sessions_set(AB_THEME_META_OG_TITLE_CACHE,$title);
        }
        else
        {
            $title=trim(strip_tags($title));
            exponent_sessions_set(AB_THEME_ACTION_DES_CACHE,$title);
            // June 21, 2011 - trungdt - Set meta OG title cache automatically
            exponent_sessions_set(AB_THEME_META_OG_CONTENT_CACHE,$title);
        }

    }
    function _ab_theme_action_clear_cache(){
        exponent_sessions_unset(AB_THEME_ACTION_CACHE);
        exponent_sessions_unset(AB_THEME_ACTION_TITLE_CACHE);
        exponent_sessions_unset(AB_THEME_ACTION_DES_CACHE);

        exponent_sessions_unset(AB_THEME_META_OG_TITLE_CACHE);
        exponent_sessions_unset(AB_THEME_META_OG_CONTENT_CACHE);
        exponent_sessions_unset(AB_THEME_META_OG_IMAGE);
    }
    function _ab_theme_action_get_pagetitle()
    {
        $temp=exponent_sessions_get(AB_THEME_ACTION_TITLE_CACHE);
        if ($temp == null)
            $temp="";
        return $temp;
    }
    function _ab_theme_action_get_description()
    {
        $temp=exponent_sessions_get(AB_THEME_ACTION_DES_CACHE);
        if ($temp == null)
            $temp="";
        return $temp;
    }
    function _ab_theme_action_get_actioncache()
    {
        $temp=exponent_sessions_get(AB_THEME_ACTION_CACHE);
        if ($temp == null)
        {
            $temp="";
        }
        return $temp;
    }

    /**
    * This function return date like Thứ 5, Thứ 6, for schedule title
    * @author: trungdt
    * @since: Feb 22
    * @param date $date: timestamp, returned by time()
    */
    function _ab_lang_dateTitle($date)
    {
        $temp=date("w",$date)+1;
        $day=date("j",$date);
        if ($temp==1)
        {
            $temp="Chúa Nhật, {$day}";
        }    
        else
        {
            $temp="Thứ {$temp}, {$day}";
        }
        return $temp;
    }
    /**
    * Function search keyword generator
    */
    function _ab_search_generate_keyword($content, $ret_string=0)
    {
        $term_status = exponent_search_cleanSearchQuery(
        @array_map("addslashes",array_map("trim",split(" ",$content))));
        if ($ret_string==1)
        {
            return implode(" ",$term_status);
        }
        else
            return $term_status;
    }

    /**
    * Function return date in Vietnamese style
    * $short_mode bool Return date format with dd/mm/yyyy or long style format
    * @param $force_not_realtime: Force, not use realtime. For example: xx min ago
    */
    function _ab_dateFormat($date_time, $short_mode=false, $force_not_realtime=false)
    {
        $now=time();  
        $date_translate = exponent_lang_loadFile('subsystems/forms/controls/yuicalendarcontrol.php');
        if (!$force_not_realtime && ($now - $date_time < 86400 ))  // 24 hours
        {

            $un_equal=$now-$date_time;
            $uh=floor($un_equal / 3600);
            $un_equal=$un_equal-3600*$uh;

            $um=floor($un_equal / 60);
            $un_equal=$un_equal-60*$um; 

            $date_time = $date_translate['ago'];
            if ($uh > 0)
            {
                $date_time.="{$uh} " . $date_translate['hour'];
            }

            if ($um > 0)
            {
                $date_time.="{$um} " . $date_translate['minute'];
            }

            //if ($un_equal > 0)
            //{
            //    $date_time.="{$un_equal} " . $date_translate['sec'];
            //}
            $date_time.=$date_translate['ago_after'];
        }
        else
        {   
            if ($short_mode == true)
            {
                $date_time = date('d/m/Y H:i', $date_time);
            }
            else
            {
                $datetime = date('l, F d, o g:i a', $date_time);
                // If the language is english, use the default language of yui calendar
                if (USE_LANG != 'eng_US') {
                    // Translate days of the week
                    // thứ
                    $datetime=$date_translate[strtolower(substr(date('l',$date_time),0,2))].", ";
                    // ngày
                    $datetime.=date('d',$date_time)." ";
                    // tháng
                    $datetime.=$date_translate[strtolower(date('F',$date_time))]." ";
                    // năm
                    $datetime.=date('o',$date_time)."; ";
                    $datetime.=date('G:i',$date_time)." ";
                    // am - pm
                    $datetime.=$date_translate[strtolower(date('a',$date_time))];
                    $date_time = $datetime;
                }
            }
        }
        return $date_time;
    }

    /**
    * Try to check field seo_name (inputed by $field)
    * 
    * @author trungdt
    * @since Oct 27, 2011
    * @param mixed $table
    * @param mixed $field
    * @param mixed $value
    * 
    * @return string Value of $field which not duplicate with any record in $table
    */
    function _ab_check_seoname($table, $value, $id=0, $field="seo_name"){
        global $db;

        $can_break=false;
        $bk_value=$value;
        do{
            $data=$db->selectObject($table, "{$field} = '{$value}' ");
            if ($data && $data->id  != $id)
                $value = $bk_value.rand(0,9999);
            else
                $can_break=true;
        } while (!$can_break);
        return $value;
    }


    function sendmail()
    {
        {
            // nov 6, 20110 - trungdt - add send type
            // =0: to all who registered
            // =1: to all normal users
            // =2: to all users
            //= 3:Register(not user)
            //= 4:Register(both user and non user)
            // = 5:Customer Select
            $obj = null;
            global $db;
            $send_type=0;
            if (isset($_REQUEST['send_type']))
                $send_type = intval($_REQUEST['send_type']);
            $emails_temp=array();
            if($send_type == 3)
            {
                $sql_where="users_id=0 and blacklist=0";
                $emails_temp=$db->selectObjects("maillinglist",$sql_where);
            }
            else if($send_type == 4)
                {
                    $sql_where="(users_id=0 or users_id>0) and blacklist = 0";
                    $emails_temp=$db->selectObjects("maillinglist",$sql_where);
                }
                else if ($send_type == 0)
                    {
                        $sql_where="blacklist=0";
                        $emails_temp=$db->selectObjects("maillinglist",$sql_where);
                    }
                    else 
                    {
                        $sql_where="is_admin = 0 AND is_acting_admin=0";
                        if ($send_type == 2) // all users
                            $sql_where="";
                        $emails_temp=$db->selectObjects("user", $sql_where);
            }


            if (count($emails_temp) == 0)
                exponent_flow_redirect(); 
            $headers = array();
            $headers['From'] =  SMTP_FROMADDRESS ;
            $headers['Reply-to'] = SMTP_FROMADDRESS;

            // fix href html content
            $content=$_REQUEST['content'];
            $content=str_replace('\"','"', $content);
            $content=str_replace("\'","'", $content);
            $content=str_replace('src="','src="' . URL_FULL,$content);
            $content=str_replace("src='","src='" . URL_FULL,$content);
            $content=str_replace('href="','href="' . URL_FULL,$content);
            $content=str_replace("href='","href='" . URL_FULL,$content);

            require_once(BASE.'subsystems/mail.php');
            $emails=array();
            // Nov 6, 2011 - trungdt - Add  %name% for Name (replace)
            $bk_content=$content;
            $obj = $db->selectObject('sysmail','');
            foreach ($emails_temp as $k=>$v)
            {
                if ($send_type >0)
                    $content=str_replace("%name%", "{$v->firstname} {$v->lastname}", $bk_content);
                //insert to sysmail this
                $date_insert = time();
                $obj->subject = $_REQUEST['subject'];
                $obj->content = $content;
                $obj->send_cc = '';
                $obj->send_cc = '';
                $obj->send_bcc = '';
                $obj->date_insert = $date_insert;
                $obj->mail_status = '0';
                $obj->date_send = '';
                $obj->error_log = '';
                $obj->send_to = $v->email; 
                $db->insertObject($obj,'sysmail');
            }    
            exponent_flow_redirect();
        }
    }
    
    /**
    * Silent Redirect (show) HTTP Error Code
    * 
    * @param mixed $error_code: 404, 403
    */
    function exponent_http_error($error_code){
        global $db;
        
        $code = "{$error_code}";
        $section_id = LANG_NUMBER.$code;
        
        $section = $db->selectObject('section','id='.$section_id);
        if ($section)
        {
            // we can redirect
            $params = array("section"=>$section_id);
            $url = exponent_core_makeLink($params, '', $section->sef_name);
            header("Location: " . $url);
        }
        else
        {
            if ($error_code == 403)
                echo SITE_403_HTML;
            else if ($error_code == 404)
                echo SITE_404_HTML;
            
        }
    }
    
    function eDebug($var, $halt=false){
        if (DEVELOPMENT) {
            echo "<xmp>";
            print_r($var);
            echo "</xmp>";

            if ($halt) die();
        }
    }

    function eLog($var, $type='', $path='', $minlevel='0') {
        if($type == '') { $type = "INFO"; }
        if($path == '') { $path = BASE . 'tmp/exponent.log'; }
        if (DEVELOPMENT >= $minlevel) {
            if (is_writable ($path) || !file_exists($path)) {
                if (!$log = fopen ($path, "ab")) {
                    eDebug("Error opening log file for writing.");
                } else {
                    if (fwrite ($log, $type . ": " . $var . "\r\n") === FALSE) {
                        eDebug("Error writing to log file ($log).");
                    }
                    fclose ($log);
                }
            } else {
                eDebug ("Log file ($log) not writable.");
            }
        }
    }
    
    /****************** For Hasan Kurtulus Law site *********/
    /**
    * Register page title to put on the other place instead of above main content
    * 
    * @param string $title
    * @author trungdt
    * @since Dec 4, 2012
    */
    function _ab_layout_settitle($title)
    {
        exponent_sessions_set("AB_THEME_PAGETITLE",$title);
    }
    
    /**
    * Get page title inside layout
    * 
    * @param string $title
    * @author trungdt
    * @since Dec 3, 2012
    */
    function _ab_layout_gettitle()
    {
        $v = exponent_sessions_get("AB_THEME_PAGETITLE");
        exponent_sessions_unset("AB_THEME_PAGETITLE");
        return $v;
    }
    
    /**
    * Register page top sentence SRC
    * 
    * @param string $title
    * @author trungdt
    * @since Dec 4, 2012
    */
    function _ab_layout_set_topsentence_src($src)
    {
        exponent_sessions_set("AB_THEME_TOP_CONTAINER_SRC",$src);
    }
    
    /**
    * Get SRC of top sentence
    * 
    * @param string $title
    * @author trungdt
    * @since Dec 3, 2012
    */
    function _ab_layout_get_topsentence_src()
    {
        $v=exponent_sessions_get("AB_THEME_TOP_CONTAINER_SRC");
        exponent_sessions_unset("AB_THEME_TOP_CONTAINER_SRC");
        return $v;
        
    }
    
    /**
    * Scan virus of selected file using clamdscan
    * @author trungdt
    * @since Jan 31, 2013
    * @ret: true of infected by virus, false of not
    */
    function _ab_clamdscanvirus($file)
    {
        // clamdscan --fdpass file
        // dont scan in localhost running
        if ($_SERVER['SERVER_ADDR'] == "127.0.0.1")
            return false;
            
        $command = "clamdscan --fdpass {$file}";
        $command = escapeshellcmd($command);
        
        $ret2="";
        $ret=exec($command, $ret2);
        
        foreach ($ret2 as $st){
            if (strpos($st, "FOUND")>0)
                return true;
        }
        
        return false;
    }
    
?>
